package com.singlemountaintech.haogongjiang.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

/**
 * Created by LUOLI on 2017/10/23.
 * <p>
 * 使用方法
 * ①找控件
 * BackEditText etNum = findViewById(R.id.register_et_num);
 * ②监听  此监听是在EditText有焦点时点击返回键触发的
 * etNum.setBackListener(new BackEditText.BackListener() {
 *
 * @Override public void back(EditText editText) {
 * // 在此将焦点转移到根视图，以使EditText失去焦点
 * View rootView = getRootView();
 * rootView.setFocusableInTouchMode(true);
 * rootView.setFocusable(true);
 * rootView.requestFocus();
 * }
 * });
 */

@SuppressLint("AppCompatCustomView")
public class BackEditText extends EditText {
    public BackEditText(Context context) {
        super(context);
    }

    public BackEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
//        setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                EditText editText = (EditText) v;
//                String string = editText.getText().toString();
//                editText.setSelection(string.length());
//                return false;
//            }
//        });
    }

    public BackEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public interface BackListener {
        void back(EditText editText);
    }


    private BackListener listener;

    public void setBackListener(BackListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (listener != null) {
                listener.back(this);
            }
        }
        return false;
    }
}
